package com.tzxs.pay.util;


import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtil {
    private static final String TAG = RetrofitUtil.class.getSimpleName();
    private static RetrofitUtil INSTANCE;

    public ApiService apiService;

    private static final String baserUrl = ApiService.baseUrl;

    private RetrofitUtil() {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new HttpLoggingInterceptor())
                .addInterceptor(chain -> {
                    //添加head头部
                    // TODO: 2018/5/22 切换分支后需要将v2改为v1
                    Request request = chain.request().newBuilder()
                            .addHeader("Accept", "application/vnd.api-demo.v2+json")
                            .build();
                    return chain.proceed(request);
                })
                .addNetworkInterceptor(new HttpLoggingInterceptor())
                .readTimeout(5000, TimeUnit.SECONDS)
                .writeTimeout(3000, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baserUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build();
        apiService = retrofit.create(ApiService.class);

    }


    /**
     * 获取到单例
     *
     * @return INSTANCE
     */
    public static RetrofitUtil getInstance() {

        if (INSTANCE == null) {
            synchronized (RetrofitUtil.class) {
                if (INSTANCE == null) {
                    INSTANCE = new RetrofitUtil();
                }
            }
        }

        return INSTANCE;
    }
}
